var that
class Tab {
  constructor(id) {
    that = this
    // 获取元素
    this.main = document.querySelector(id)
    this.add = this.main.querySelector('.tabadd')
    // li的父元素
    this.ul = this.main.querySelector('.tabnav ul:first-child')
    // section 父元素
    this.fsection = this.main.querySelector('.tabcon')
    this.init()
  }
  init() {
    this.updateNode()
    // init 初始化操作让相关的元素绑定事件
    this.add.onclick = this.addTab
    for (let i = 0; i < this.lis.length; i++) {
      this.lis[i].index = i
      this.lis[i].onclick = this.toggleTab
      this.remove[i].onclick = this.removeTab
      this.spans[i].ondblclick = this.editTab
      this.sections[i].ondblclick = this.editTab
    }
  }
  // 动态添加或删除元素 需要重新获取对应的元素
  updateNode() {
    this.lis = this.main.querySelectorAll('li')
    this.sections = this.main.querySelectorAll('section')
    this.remove = this.main.querySelectorAll('.icon-guanbi')
    this.spans = this.main.querySelectorAll('.tabnav li span:first-child')
  }
  // 1. 切换功能
  toggleTab() {
    // console.log(this.index)
    that.clearClass()
    this.className = 'liactive'
    that.sections[this.index].className = 'conactive'
  }
  clearClass() {
    for (let i = 0; i < this.lis.length; i++) {
      this.lis[i].className = ''
      this.sections[i].className = ''
    }
  }
  // 2. 添加功能
  addTab() {
    that.clearClass()
    // (1) 创建li元素和section元素
    let random = Math.random()
    let li =
      '<li class="liactive"><span>New Tab</span><span class="iconfont icon-guanbi"></span></li>'
    let section = '<section class="conactive">Test ' + random + '</section>'
    // (2) 把两个元素追加到对应的父元素里面
    that.ul.insertAdjacentHTML('beforeend', li)
    that.fsection.insertAdjacentHTML('beforeend', section)
    that.init()
  }
  // 3. 删除功能
  removeTab(e) {
    e.stopPropagation() // 阻止冒泡 防止触发li 的切换点击事件
    let index = this.parentNode.index
    // console.log(index)
    // 根据索引删除对应的li 和section
    that.lis[index].remove()
    that.sections[index].remove()
    that.init()
    // 当删除不是选中状态的li时候 正处于选中状态的li 保持不变
    if (document.querySelector('.liactive')) return
    // 当删除选中状态的li的时候 让它前一个li 处于选中状态
    index--
    // 自动触发点击事件 不需要手动点击
    that.lis[index] && that.lis[index].click()
  }
  // 4. 修改功能
  editTab() {
    let str = this.innerHTML
    // 双击禁止选定文字
    window.getSelection
      ? window.getSelection().removeAllRanges()
      : document.getSelection.emply()
    this.innerHTML = '<input type="text"/>'
    let input = this.children[0]
    input.value = str
    input.select() // 使文本框内容处于选定状态
    // 当离开文本框时 把文本框里的值给span
    input.onblur = function () {
      this.parentNode.innerHTML = this.value
    }
    // 按下回车也可以文本框里的值给span
    input.onkeyup = function (e) {
      if (e.keyCode === 13) {
        // 手动调用文本框失去焦点事件
        this.blur()
      }
    }
  }
}

new Tab('#tab')
